import os

from genson import SchemaBuilder
from jsonschema import validate



def join_path(dir_path, filename):
    path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), dir_path, filename)

    return path


def save_jsonshema(filename, date_dict):
    path = join_path("config", filename)
    date = build_schema(date_dict)
    with open(path, mode="w", encoding="utf-8") as file:
        file.write(date)


# 全量校验-生成校验规则
def build_schema(date_dict):
    builder = SchemaBuilder()
    builder.add_object(date_dict)

    return builder.to_json(indent=2)  # builder.to_schema()生成的是字符串形式的json


def schema_validate(obj, schema):
    try:
        validate(instance=obj, schema=schema)
        return True
    except Exception as e:
        from api_qiyeweixin.untils.log_until import logger

        logger.info(f"全量校验失败：{e}")
        return False


def load_jsonshema(filename):
    path = join_path("config", filename)
    with open(path, mode='r', encoding="utf-8") as file:
        date = file.read()

    return date
